<?php
namespace haibao\app\data;

class StationMessage extends \haibao\app\data\BaseMysql{

	public function __construct(){
		parent::__construct('\haibao\app\model\data\StationMessage');
	}
	
	/**
	 * 计划任务跑预发布消息状态
	 */
	public function publishMessage(){
		$today = date('Y-m-d H:i:s',time());
		$sql = "update StationMessage set Published=".\haibao\app\model\data\StationMessage::PUBLISHED_YES." where Published =".\haibao\app\model\data\StationMessage::PUBLISHED_PRE.' and PublishTime <="'.$today.'" and Status ='.\haibao\app\model\data\StationMessage::STATUS_ENABLE;
		$this->query ($sql);
	}

	/**
	 * 添加站内消息
	 */
	public function saveStationMessage($model){
		$this->beginTranscation();
		try {
			$model->ReadCount = 0;
			$this->add($model);
			if($model->UserId){
				$userStr = $model->UserId;
				$userStr = str_replace("，",",",$userStr);
				$userArr = explode(',',$userStr);
				$userArr = array_unique($userArr);
				$this->addUserMessage($model->Id, $userArr);
			}
		} catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	/**
	 * 添加站内消息关联个别用户
	 */
	private function addUserMessage($messageId, $userArr){
		$CreateTime = new \DateTime();
		if(is_array($userArr)){
			$sql = 'insert into UserMessage(`MessageId`,`UserId`,`CreateTime`) values ';
			$arrSql = $arrValues = array();
			foreach($userArr as $userId){
				if($userId != ''){
					array_push($arrSql, '(%s,%s,%s)');
					array_push($arrValues, $messageId);
					array_push($arrValues, $userId);
					array_push($arrValues, $CreateTime);
				}
			}
			if($arrSql && $arrValues){
				$sql .= implode(',', $arrSql);
				$this->query($sql, $arrValues);
			}
		}else {
			$sql = 'insert into UserMessage(`MessageId`,`UserId`,`CreateTime`) values(%s,%s,%s)';
			$this->query($sql,array(
					$messageId,$userArr,$CreateTime
			));
		}
		
	}
	
	/**
	 * 删除站内消息（修改状态）
	 */
	public function updateMessageStatus($messageId, $status){
		$this->beginTranscation();
		try {
			$this->query('update StationMessage set Status=%s where Id=%s limit 1', array(
					$status, $messageId
			));
			
			if($status == \haibao\app\model\data\StationMessage::STATUS_DISABLE){
				$this->query('delete from UserMessage where MessageId = %s', array(
						$messageId
				));
			}
			
		} catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}

}